<template>
  <div id="userLoginView">
    <h2 style="margin-bottom: 16px">用户登录</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      @submit="handleSubmit"
    >
      <a-form-item field="userAccount" label="账号">
        <a-input v-model="form.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item field="userPassword" tooltip="密码不少于 8 位" label="密码">
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          style="width: 120px"
          :loading="isLoading"
        >
          {{ isLoading ? "登录中..." : "登录" }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { UserControllerService, UserLoginRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";

/**
 * 表单信息
 */
const form = reactive({
  userAccount: "",
  userPassword: "",
} as UserLoginRequest);

const router = useRouter();
const route = useRoute();
const store = useStore();
const isLoading = ref(false);

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (isLoading.value) {
    return; // 防止重复提交
  }

  // 表单验证
  if (!form.userAccount || !form.userPassword) {
    message.error("请输入账号和密码");
    return;
  }

  if (form.userPassword.length < 8) {
    message.error("密码不少于8位");
    return;
  }

  isLoading.value = true;

  try {
    console.log("开始登录...");
    const res = await UserControllerService.userLoginUsingPost(form);

    // 登录成功
    if (res.code === 0) {
      console.log("登录成功：", res);
      message.success("登录成功！");

      try {
        // 更新用户状态
        console.log("更新用户状态...");
        await store.dispatch("user/getLoginUser");

        // 获取重定向地址
        const redirect = route.query.redirect as string;
        const targetPath =
          redirect && redirect !== "/user/login" ? redirect : "/";

        console.log("跳转到:", targetPath);

        // 使用 replace 避免在浏览器历史中留下登录页
        await router.replace(targetPath);
      } catch (error) {
        console.error("用户状态更新失败:", error);
        // 即使状态更新失败，也尝试跳转
        await router.replace("/");
      }
    } else {
      console.error("登录失败:", res);
      message.error(res.message || "登录失败，请检查账号密码");
    }
  } catch (error) {
    console.error("登录请求失败:", error);
    message.error("网络请求失败，请稍后重试");
  } finally {
    isLoading.value = false;
  }
};
</script>
